/***************************************************************************
 *   Copyright (C) 2010 by Oleg Goncharov  *
 *   $EMAIL$                           *                          
 *                                                                         *
 *   This file is part of ChessVision.                                     *
 *                                                                         *
 *   ChessVision is free software; you can redistribute it and/or modify   *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include <cmath>
#include <iostream>

#include <opencv/cv.h>
#include <opencv/highgui.h>

#include "define.h"
#include "choughdetector.h"

namespace Chess {

CHoughDetector::CHoughDetector() {	
	step_h = 2;
	step_teta = PI /30.0;
	xystep_mul = 4;
	
}

void CHoughDetector::CalcLimitsSteps(CvSize size, float h) {
	float tmp = 4*sqrtf(2.0f)*h;
	
	O_rect.x1 = tmp; O_rect.y1 = tmp;
	O_rect.x2 = size.width - tmp; O_rect.y2 = size.height - tmp;
	
	step_x = step_y = 7*h*sin(step_teta) / xystep_mul;
}

bool CHoughDetector::DetectChessboard(IplImage * img, CBoardCells& cells) {
	double best = 0, tmp;
	SBoardPosition v;
	CvSize size = cvGetSize(img);
	SBoardPosition bp;
	
	max_h =  MIN(size.height, size.width) / 8;
	min_h = max_h / 2;
	
	IplImage * grey = cvCreateImage(size, IPL_DEPTH_8U, 1);
	cvCvtColor(img, grey, CV_BGR2GRAY);
	
	for(v.h = min_h; v.h <= max_h; v.h += step_h) {
		CalcLimitsSteps(size , v.h);
		
		for(v.teta = 0.0f; v.teta <= PIf; v.teta += step_teta) 
			for(v.x = O_rect.x1; v.x <= O_rect.x2; v.x += step_x) 
				for(v.y = O_rect.y1; v.y <= O_rect.y2; v.y += step_y) {
					tmp = Integral(grey, v, int(v.h/3));
					
					if (tmp >= best) {
						best = tmp;
						bp = v;
					}
				}
	}
	
	cvReleaseImage(&grey);
	
	cells.Init(bp);
//TODO Обнаружение/не обнаружение доски 
	return true;
}

}

